<template>
  <div class="app-container">
    <h3 v-if="parentId === 0">一级分区目录</h3>
    <h3 class="back-link" v-if="parentId !== 0" @click="back">返回上级目录</h3>
    <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets" style="margin-top: 5px"></i>
      <span style="margin-top: 5px">数据列表</span>
      <el-button class="btn-add" @click="handleAdd()" size="mini">
        添加
      </el-button>
    </el-card>
    <div class="table-container">
      <el-table
        ref="productCateTable"
        style="width: 100%"
        :data="list"
        v-loading="listLoading"
        border
      >
        <el-table-column label="编号" width="70" align="center">
          <template slot-scope="scope">{{ scope.row.id }}</template>
        </el-table-column>
        <el-table-column label="分区名称" align="center">
          <template slot-scope="scope">{{ scope.row.partitionName }}</template>
        </el-table-column>
        <el-table-column label="级别" width="100" align="center">
          <template slot-scope="scope">{{
            scope.row.partitionLevel | levelFilter
          }}</template>
        </el-table-column>

        <el-table-column label="创建人" width="100" align="center">
          <template slot-scope="scope">{{ scope.row.creatorName }}</template>
        </el-table-column>
        <el-table-column label="创建时间" width="160" align="center">
          <template slot-scope="scope">{{ scope.row.ctime }}</template>
        </el-table-column>
        <el-table-column label="修改人" width="100" align="center">
          <template slot-scope="scope">{{ scope.row.updateName }}</template>
        </el-table-column>
        <el-table-column label="修改时间" width="160" align="center">
          <template slot-scope="scope">{{ scope.row.mtime }}</template>
        </el-table-column>
        <el-table-column label="备注信息" width="200" align="center">
          <template slot-scope="scope">{{ scope.row.info }}</template>
        </el-table-column>
        <el-table-column label="排序" width="100" align="center">
          <template slot-scope="scope">{{ scope.row.sort }}</template>
        </el-table-column>
        <el-table-column label="设置" width="150" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              :disabled="scope.row.partitionLevel | disableNextLevel"
              @click="handleShowNextLevel(scope.$index, scope.row)"
              >查看下级
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="handleUpdate(scope.$index, scope.row)"
              >编辑
            </el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper"
        :page-size="listQuery.pageSize"
        :page-sizes="[10, 15, 20]"
        :current-page.sync="listQuery.pageNum"
        :total="total"
      >
      </el-pagination>
    </div>
    <el-dialog
      :title="isEdit ? '编辑分区' : '添加分区'"
      :visible.sync="dialogVisible"
      width="30%"
      center
    >
      <el-form
        :model="partition"
        :rules="rules"
        ref="partitionFrom"
        label-width="150px"
      >
        <el-form-item label="分区名称：" prop="partitionName">
          <el-input v-model="partition.partitionName"></el-input>
        </el-form-item>
        <el-form-item label="上级分区：" prop="parentId">
          <el-cascader
            v-model="selectPartitionValue"
            :options="partitionOptions"
            :show-all-levels="false"
            :props="{ checkStrictly: true }"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="排序：">
          <el-input v-model="partition.sort"></el-input>
        </el-form-item>
        <el-form-item label="分区描述：">
          <el-input
            type="textarea"
            placeholder="请输入内容"
            v-model="partition.info"
            maxlength="255"
            show-word-limit
          >
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="onSubmit('partitionFrom')"
          size="small"
          >提交</el-button
        >
        <el-button
          v-if="!isEdit"
          @click="resetForm('partitionFrom')"
          size="small"
          >重置</el-button
        >
        <el-button @click="dialogVisible = false" size="small">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  fetchList,
  deletePartition,
  createPartition,
  updatePartition,
  fetchListWithChildren,
} from "@/api/partition";
const defaultPartition = {
  partitionName: null,
  parentId: 0,
  info: null,
  sort: 1,
  id: null,
};
export default {
  name: "partitionList",
  data() {
    return {
      list: null,
      total: null,
      listLoading: true,
      listQuery: {
        pageNum: 1,
        pageSize: 10,
      },
      parentId: 0,
      dialogVisible: false,
      partition: Object.assign({}, defaultPartition),
      selectPartitionList: [],
      selectPartitionValue: [],
      partitionOptions: [],
      rules: {
        partitionName: [
          { required: true, message: "请输入分区名称", trigger: "blur" },
          {
            min: 2,
            max: 100,
            message: "长度在 1 到 100 个字符",
            trigger: "blur",
          },
        ],
        parentId: {
          required: true,
          message: "请选择上级分区",
          trigger: "blur",
        },
      },
      isEdit: false,
    };
  },
  created() {
    this.resetParentId();
    this.getList();
    this.getPartitionOptions();
  },
  watch: {
    $route(route) {
      this.resetParentId();
      this.getList();
    },
    selectPartitionValue: function (newValue) {
      if (newValue !== null) {
        this.partition.parentId = newValue[newValue.length - 1];
      } else {
        this.partition.parentId = null;
      }
    },
  },
  methods: {
    back() {
      // 返回上级
      if (this.parentId !== 0) {
        this.$router.back();
      }
    },
    resetParentId() {
      this.listQuery.pageNum = 1;
      if (this.$route.query.parentId != null) {
        this.parentId = this.$route.query.parentId;
      } else {
        this.parentId = 0;
      }
    },
    handleAdd() {
      this.dialogVisible = true;
      this.isEdit = false;
      this.partition = Object.assign({}, defaultPartition);
      this.selectPartitionValue = this.partitionOptions[0].value;
    },
    getList() {
      this.listLoading = true;
      fetchList(this.parentId, this.listQuery).then((response) => {
        this.listLoading = false;
        this.list = response.data.list;
        this.total = response.data.total;
      });
    },
    handleSizeChange(val) {
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.pageNum = val;
      this.getList();
    },
    handleShowNextLevel(index, row) {
      this.$router.push({
        path: "/cms/partition",
        query: { parentId: row.id },
      });
    },
    handleUpdate(index, row) {
      this.dialogVisible = true;
      this.isEdit = true;
      // console.log(row);
      this.partition = Object.assign({}, row);
      this.handleChangeSelectPartitionValue();
    },
    handleChangeSelectPartitionValue() {
      this.selectPartitionValue = [];
      for (let i = 0; i < this.partitionOptions.length; i++) {
        let item = this.partitionOptions[i];
        if (item.value == this.partition.parentId) {
          this.selectPartitionValue.push(item.value);
          return;
        }
        // console.log(item.children);
        if (item.children !== null && item.children !== undefined) {
          for (let j = 0; j < item.children.length; j++) {
            let child = item.children[j];
            if (child.value == this.partition.parentId) {
              this.selectPartitionValue.push(item.value);
              this.selectPartitionValue.push(child.value);
              return;
            }
          }
        }
      }
      if (this.selectPartitionValue.length === 0) {
        this.selectPartitionValue = [0];
      }
    },
    handleDelete(index, row) {
      this.$confirm(
        "删除分区会导致分区下属内容进入审核未通过状态，是否删除?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(() => {
        deletePartition(row.id).then((response) => {
          this.$message({
            message: "删除成功",
            type: "success",
            duration: 1000,
          });
          this.getList();
        });
      });
    },
    getPartitionOptions() {
      fetchListWithChildren().then((res) => {
        let list = res.data;
        this.partitionOptions = [];
        for (let i = 0; i < list.length; i++) {
          let secondChildren = [];
          let secondChildrenList = list[i].children;
          if (secondChildrenList != null && secondChildrenList.length > 0) {
            for (let j = 0; j < secondChildrenList.length; j++) {
              secondChildren.push({
                label: secondChildrenList[j].partitionName,
                value: secondChildrenList[j].id,
              });
            }
          }
          // 存一级分区
          this.partitionOptions.push({
            label: list[i].partitionName,
            value: list[i].id,
            children: secondChildren.length === 0 ? null : secondChildren,
          });
        }
        this.partitionOptions.unshift({
          value: "0",
          label: "无上级分区",
        });
      });
    },
    onSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$confirm("是否提交数据", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => {
            if (this.isEdit) {
              // console.log(this.partition);
              updatePartition(this.partition.id, this.partition).then(
                (response) => {
                  this.$message({
                    message: "修改成功！",
                    type: "success",
                  });
                  this.dialogVisible = false;
                  this.getList();
                }
              );
            } else {
              createPartition(this.partition).then((response) => {
                this.$refs[formName].resetFields();
                this.resetForm(formName);
                this.$message({
                  message: "提交成功",
                  type: "success",
                  duration: 1000,
                });
                this.dialogVisible = false;
                this.getList();
              });
            }
          });
        } else {
          this.$message({
            message: "验证失败",
            type: "error",
            duration: 1000,
          });
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.partition = Object.assign({}, defaultPartition);
      this.getPartitionOptions();
    },
  },

  filters: {
    levelFilter(value) {
      if (value === 0) {
        return "一级";
      } else if (value === 1) {
        return "二级";
      } else if (value === 2) {
        return "三级";
      }
    },
    disableNextLevel(value) {
      if (value === 0 || value === 1) {
        return false;
      } else {
        return true;
      }
    },
  },
};
</script>

<style scoped>
</style>
